//
//  UserCenterViewModel.m
//  Jyxt
//
//  Created by 刘日 on 17/5/25.
//  Copyright © 2017年 DaLian Rental Housing Management. All rights reserved.
//

#import "UserCenterViewModel.h"
#import "NetTool.h"
#import "ClientViewModel.h"
#import <MJExtension.h>
#import "DatabaseTool.h"
#import <LemonBubble.h>

#define UTOKEN @"uToken"
#define UNAME @"uName"

@implementation UserCenterViewModel

+ (BOOL)isHaveSignIn{
    return [DatabaseTool getWithKey: UTOKEN] != nil;
}

+ (void)gotoMain{
    [LKFreeCtrl presentViewController: [LKInstance findViewControllerInStoryboardWithKey: @"m_root"]];
}

+ (NSString *)getLocalUToken{
    return [DatabaseTool getWithKey: UTOKEN];
}

+ (void)bindSignInCheckWithNumberField: (UITextField *)numberField
                         passwordField: (UITextField *)passwordField
                          signInButton: (UIButton *)signInButton{
    [[numberField.rac_textSignal merge: passwordField.rac_textSignal] subscribeNext:^(id  _Nullable x) {
        signInButton.enabled = numberField.text.length > 0 && passwordField.text.length > 0;
    }];
    [[signInButton rac_signalForControlEvents: UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [[LKFreeCtrl getTopViewController] showRoundProgressWithTitle: @"登录中..."];
        [self signInWithNumber: numberField.text password: passwordField.text success:^{
            [[LKFreeCtrl getTopViewController] hideBubble];
            numberField.text = @"";
            passwordField.text = @"";
            [self gotoMain];
        } failed:^(NSString *reason) {
            [[LKFreeCtrl getTopViewController] showErrorWithTitle: [NSString stringWithFormat: @"登录失败 %@" , reason] autoCloseTime: 3];
        }];
    }];
}

+ (void)signInWithNumber: (NSString *)number password: (NSString *)password success: (void (^)()) success failed: (void (^)(NSString *reason))failed{
    [ClientViewModel getCTokenWithSuccess:^(NSString *ctoken) {
        [NetTool postWithUrl: APIURL(API_USER_SIGN_IN) data: @{@"ctoken" : ctoken , @"data" : @{@"username" : number , @"password" : password}.mj_JSONString} onSuccess:^(NSDictionary *response) {
            if ([response[@"success"] boolValue]) {
                NSString *uToken = response[@"utoken"];
                [DatabaseTool putWithKey: UTOKEN value: uToken];
                [DatabaseTool putWithKey: UNAME value: response[@"name"]];
                LKLog(@"注册的 token 是 :%@",uToken);
                success(uToken);
            }
            else{
                failed(response[@"errmsg"]);
            }
        } onError:^(NSError *error) {
            failed(@"无法连接到服务器");
        }];
    } failed:^(NSString *reason) {
        failed([NSString stringWithFormat: @"%@%@" ,@"注册设备失败" , reason]);
    }];
}

+ (void)signOut{
    [DatabaseTool removeWithKey: UTOKEN];
    [ClientViewModel clearLocalCToken];
    [[LKFreeCtrl getTopViewController] dismissViewControllerAnimated: YES completion: nil];
}

@end
